import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.text.SimpleDateFormat;

class ServerCheck 
{
	public static void main(String[] args) {
		ServerCheck serverCheck = new ServerCheck();
		serverCheck.start();
	}
	
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
//	String accessToken = "AAAE0jcVbRx4BAF1BZBZBLVIl5N0EjY3kLPhNX2XQphCoM7TQ1aTJ7NmTFHuJZCBmC1pD0x0IpvDl6mtH0e1hNx234J5lDfs64EEDHPtkQZDZD";
	String accessToken = "AAAE0jcVbRx4BAJTqdBicIpibkJiWE9ZBO9xwP3Tl6tJEQAAiFcYfdpdrhFFQIoKBV9jW1M5WZAn1mlgBoG6RzaXecqQzE6TNkFwCui4QZDZD";
	String programName = "[서버 상태 체크 프로그램]\n";
//	String groupId = "186577728129797";	//도라에몽 그룹ID
//	String groupId = "319611651466850";	//에너지관리공단 그룹ID
	String groupId = "118022295029609";	//신재생에너지 서버체크

	String koreaUrl 	= "https://www.renewableenergy.or.kr/sti/adisvc/selectMobile.do";
	String englishUrl 	= "http://www.renewableenergy-korea.com/aboutUs/siteInfo.do";
	String mobileUrl 	= "http://m.renewableenergy.or.kr/cst/sitemap/selectSitemap.do";

	String koreaMessage = "";
	String englishMessage = "";
	String mobileMessage = ""; 
	
	int koreaStateCode = 0;
	int englishStateCode = 0;
	int mobileStateCode = 0;
	
	public void start() {
		
		while(true) {
			
			int koreaResultCode = checkServer(koreaUrl);
			if(koreaResultCode==200) {
				koreaMessage = "국문서버 살아있음.";
				koreaStateCode = 1;
			} else {
				koreaMessage = "삼가 국문서버의 명복을 빕니다.";
				//페이스북 알림 
				if( koreaStateCode == 1) {
					koreaStateCode = 0;
					facebookSend(accessToken, groupId, programName + koreaMessage);
				}
			}
			System.out.println(dateFormat.format(new java.util.Date()) + " : (" + koreaResultCode + ") " + koreaMessage);
	
			int englishResultCode = checkServer(englishUrl);
			if(englishResultCode==200) {
				englishMessage = "영문서버 살아있음.";
				englishStateCode = 1;
			} else {
				englishMessage = "삼가 영문서버의 명복을 빕니다.";
				
				//페이스북 알림 
				if( englishStateCode == 1) {
					englishStateCode = 0;
					facebookSend(accessToken, groupId, programName + englishMessage);
				}
			}
			System.out.println(dateFormat.format(new java.util.Date()) + " : (" + englishResultCode + ") " + englishMessage);
			  
			int mobileResultCode = checkServer(englishUrl);
			if(mobileResultCode==200) {
				mobileMessage = "모바일서버 살아있음.";
				mobileStateCode = 1;
			} else {
				mobileMessage = "삼가 모바일서버의 명복을 빕니다.";
				
				//페이스북 알림 
				if( mobileStateCode == 1 ) {
					mobileStateCode = 0;
					facebookSend(accessToken, groupId, programName + mobileMessage);
				}
			}
			System.out.println(dateFormat.format(new java.util.Date()) + " : (" + mobileResultCode + ") " + mobileMessage);
			
			try { Thread.sleep(1000 * 10); } catch (InterruptedException e) { }
		}
	}
	
	/**
	 * 서버 상태를 체크한다.
	 * @param checkUrl
	 * @return
	 */
	public int checkServer(String checkUrl) {
		HttpURLConnection conn = null;
		int resultCode = 502;
		try {
			URL url = new URL(checkUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setConnectTimeout(1000 * 60 * 2);	// 2분
			conn.setReadTimeout(1000 * 60 * 5);		// 5분		
			conn.setInstanceFollowRedirects(false);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlendcoded");
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.connect();
	
			resultCode = conn.getResponseCode();
						
		} catch (MalformedURLException me) {
			me.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(conn!=null) try { conn.disconnect(); }catch(Exception e) { }
		}
		
		return resultCode;
	}
	
	/**
	 * 페이스북에 메세지를 업로드한다.
	 * @param accessToken
	 * @param groupId
	 * @param message
	 */
	public void facebookSend(String accessToken, String groupId, String message) {
		URL url = null;
		HttpURLConnection http = null;
		OutputStreamWriter outStream = null;
		PrintWriter writer = null;
		try { 
			url = new URL("https://graph.facebook.com/" + groupId + "/feed?access_token=" + accessToken);
			http = (HttpURLConnection) url.openConnection();
			
			http.setDefaultUseCaches(false);
			http.setDoInput(true); 			// 서버에서 읽기 모드 지정
			http.setDoOutput(true); 		// 서버로 쓰기 모드 지정
			http.setRequestMethod("POST"); 	// 전송 방식은 POST
			http.setRequestProperty("content-type", "application/x-www-form-urlencoded");
			
			// --------------------------
			// 서버로 값 전송
			// --------------------------
			StringBuffer buffer = new StringBuffer();
			buffer.append("message").append("=").append(message);
			
			outStream = new OutputStreamWriter(http.getOutputStream(), "UTF-8");
			writer = new PrintWriter(outStream);
			writer.write(buffer.toString());
			writer.flush();
			
			// 서버에서 전송받기 
            InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "UTF-8");
            BufferedReader reader = new BufferedReader(tmp); 
            StringBuilder builder = new StringBuilder(); 
            String str; 
            while ((str = reader.readLine()) != null) {   
                builder.append(str + "\n");                    
            } 
            String myResult = builder.toString(); 
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(writer!=null) writer.close();
			if(outStream!=null) {try { outStream.close(); } catch (IOException e){ }}
			if(http!=null) http.disconnect();
		}
		System.out.println("facebook: " + message);
	}
}
